<template>
  <t-dialog
      header="修改链连接"
      :visible.sync="showDialog"
      @confirm="onConfirm"
      width='50%'
    >
    <!-- <t-select>
      :popup-props="{ 'on-scroll-to-bottom': handleScrollToBottom }"
    </t-select> -->
    <t-space size="32px">
    <t-form
      :data="formData"
      labelWidth="calc(2em + 50px)"
      labelAlign="right"
      Align="right"
      :rules="formRules"
      :layout="layout"
      ref="form"
      scrollToFirstError="smooth"
    >
      <t-form-item label="链名称" name="chain_name">
        <t-input v-model="formData.name" placeholder="请输入链名称" ></t-input>
      </t-form-item>
      <t-form-item label="链ID" name="chain_id">
        <t-input v-model="formData.chainid"  placeholder="请输入链id"></t-input>
      </t-form-item>
      <t-form-item label="AuthType" name="auth_type" layout="inline">
        <t-select
          v-model="formData.auth_type"
          :style="{ width: '222px' }"
          class="demo-select-base"
          placeholder="请选择类型"
          clearable
        >
          <t-option v-for="(item, index) in AUTH_TYPE_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="Crypto" name="crypto_hash" layout="inline">
        <t-select
          v-model="formData.crypto_hash"
          :style="{ width: '222px' }"
          placeholder="请选择类型"
          class="demo-select-base"
          clearable
        >
          <t-option v-for="(item, index) in CRYPTO_HASH_OPTIONS" :key="index + item.path" :value="item.value" :label="item.label">
            {{ item.label }}
          </t-option>
        </t-select>
      </t-form-item>
      <t-form-item label="Crypto-config" name="Crypto-config" labelWidth="calc(2em + 100px)">
        <div class="tdesign-demo-upload">
        <div style="width: 500px">
          <t-upload
            :tips="tips"
            v-model="files"
            :action="uploadApi"
            :beforeUpload="beforeUpload"
            @fail="handleFail"
            @success="onSuccess"
            theme="file-input"
            
            :multiple=false
            placeholder="未选择文件"
          ></t-upload>
        </div>
        </div>
      </t-form-item>
      <t-form-item v-for="(item, index) in formData.node_list" :key="index" label="节点地址" :name="item.node_name">
        <!-- <t-form-item v-for="(item, index) in addlist" :key="item.id" label="节点地址" :name="item.name"></t-form-item> -->
        <t-input v-model="item.node_name" placeholder="请输入节点名称" style="margin-right: 10px;"></t-input>
        <t-input v-model="item.node_ipaddr"  placeholder="请输入节点ip:port"></t-input>
        <t-button
          v-if="index === 0 || index === lastAddNodeList - 1"
          @click="addNodeList"
          slot="statusIcon"
          variant="dashed"
        >
          <icon name="add" />
        </t-button>
        <t-button v-if="index> 0" @click="removeNodeList(item, index)" slot="statusIcon" variant="dashed">
          <icon name="remove" /></t-button>
      </t-form-item>

      <t-form-item :statusIcon="false" style="margin-left: 80px">
      </t-form-item>
    </t-form>
  </t-space>
  <t-dialog
      theme="success"
      header="提示"
      body="修改成功"
      :visible.sync="prompt"
      @confirm="promptClose"
      :cancelBtn="null"
    />
  </t-dialog>
</template>

<script lang="jsx">
import { Icon } from 'tdesign-icons-vue';
import { getChainConnInfo, operateChainConn } from '@/api/requestApi';
import {
  AUTH_TYPE_STATUS,
  AUTH_TYPE_OPTIONS,
  CRYPTO_HASH_STATUS,
  CRYPTO_HASH_OPTIONS,
} from '@/constants';


const INITIAL_FORM_DATA = {
  chain_id: '',
  chain_name: '',
  node_list: [],
  auth_type: undefined,
  crypto_hash: undefined,
  crypto_config: '',
};
const FORM_RULES = {
  chain_name: [{ required: true, message: '请输入链名称', type: 'error', trigger: 'blur'}],
  auth_type: [{ required: true, message: '请选择认证类型', type: 'error', trigger: 'blur' }],
  crypto_hash: [{ required: true, message: '请选择加密算法', type: 'error', trigger: 'blur' }],
  chain_id: [{ required: true, message: '请输入ChainID', type: 'error', trigger: 'blur' }],
};

export default {
  name: 'ModifyDialogComp',
  components: {
    Icon,
  },
  props: {
    showChildDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {    
      layout: 'vertical', // 布局
      files: [], // 文件上传
      uploadApi: '/api/crypto/upload',
      tips: '请上传crpto-config.zip(.tar.gz)', // 文件上传
      lastAddNodeList: 1,
      formData: {...INITIAL_FORM_DATA},
      formRules: {...FORM_RULES},
      AUTH_TYPE_STATUS,
      AUTH_TYPE_OPTIONS,
      CRYPTO_HASH_STATUS,
      CRYPTO_HASH_OPTIONS,
      prompt: false,
    };
  },
  
  computed: {
    showDialog: {
      get() {
        return this.showChildDialog
      },
      set(newValue) {
        this.$emit('update:showChildDialog', newValue) // 触发更新事件，父组件的showDialogAdd会自动更新
      }
    }

  },
  mounted() {
    // this.$refs.formValidatorStatus.validate();
    // this.dataLoading = true;
    
  },
  methods: {
    // findKeyByValue(obj, value) {
    //   const result = Object.entries(obj).find(([key, val]) => val === value);
    //   return result ? result[0] : null;
    // },
    init(data) {
      // console.log('来自父组件的', data);
      // 根据传入id查询链连接详情
      const idx = data.id.toString();
      getChainConnInfo(idx)
        .then((res) => {
          console.log(res.data)
          if (res.data.code === '000') {
            this.formData = res.data.data
            if (this.formData.node_list !== ''){
              this.formData.node_list = JSON.parse(this.formData.node_list);
            }
            console.log('链info--->', this.formData.node_list)
            this.files.push({'name': this.formData.crypto_config});
          } else {
            this.$message.error(res.data.msg);
          }     
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e)
          
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },

    onConfirm() {
      const reqParam = {"ids": [], "param": {}, "op_type": ''};
      reqParam.param = this.formData;
      reqParam.op_type = 2;
      reqParam.ids.push(this.formData.id.toString());
      // console.log('上传目录---->', this.files[0].name)
      this.formData.crypto_config = this.files[0].name;
      // console.log("提交的表单内容", reqParam);
      operateChainConn(reqParam)
        .then((res) => {
          console.log(res.data.code)
          if (res.data.code === '000') {
            this.$message.success(res.data.msg);
            this.prompt = true;
          }
        })
        .catch((e) => {
          this.$message.error('系统异常');
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
      this.showDialog = false;
      this.$emit('modifyFlush')
    },
    
    formatResponse(res) {
      // 响应结果添加上传时间字段，用于 UI 显示
      console.log(res)
      return res;
    },
    // 文件上传-失败
    handleFail({ file }) {
      this.$message.error(`文件 ${file.name} 上传失败`);
    },
    // 文件上传-成功
    onSuccess({file}) {
      // console.log(file,file.response.data.files_path);
      file.name = file.response.data.files_path;
      this.crypto_config = file.name;
    },
    beforeUpload(file) {
      if ((!/(\.(zip)|\.(gz))$/.test(file.name))) {
        this.$message.warning('请上传zip或tar.gz压缩包');
        return false;
      }
      return true;
    },
    addNodeList() {
      this.formData.node_list.push({ node_name: '', node_ipaddr: '' });
      this.nodeListNum += 1;
    },
    removeNodeList(item, index) {
      delete INITIAL_FORM_DATA[`add${item.id}`];
      this.formData.node_list.splice(index, 1);
    },
    promptClose () {
      this.prompt = false;
      window.reload()
    }
  },
 
  
};
</script>

<style lang="less" scoped>
</style>